package org.malred.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.malred.io.Resources;
import org.malred.pojo.Configuration;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 解析配置文件，封装Configuration
     *
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) {
        try {
            // sqlMapConfig.xml
            Document document = new SAXReader().read(inputStream);
            // <configuration/>
            Element rootElement = document.getRootElement();
            // XPath表达式 查询所有 <property/>
            List<Element> property_doms = rootElement.selectNodes("//property");
            // 存放kv结构(name:value)
            Properties properties = new Properties();
            for (Element property : property_doms) {
                // 拿到name和value属性对应的值
                // <property name="xxx" value="xxx" />
                String name = property.attributeValue("name");
                String value = property.attributeValue("value");
                // 保存
                properties.setProperty(name, value);
            }
            // 创建连接池
            ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
            try {
                comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
                comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
                comboPooledDataSource.setUser(properties.getProperty("username"));
                comboPooledDataSource.setPassword(properties.getProperty("password"));
            } catch (PropertyVetoException e) {
                throw new RuntimeException(e);
            }
            // 保存datasource信息
            configuration.setDataSource(comboPooledDataSource);
            // mapper.xml解析: 拿到路径--字节输入流--dom4j解析
            List<Element> mapper_doms = rootElement.selectNodes("//mapper");
            for (Element mapper : mapper_doms) {
                String path = mapper.attributeValue("resource");
                InputStream resourceAsStream = Resources.getResourceAsStream(path);
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
                xmlMapperBuilder.parse(resourceAsStream);
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        return configuration;
    }
}
